﻿<%@ WebHandler Language="C#" Class="BomRquestCancelVue3PageHandler" %>

/* Description:配套单撤销管理后端接口
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan 
 * create Date:2025.10.21
 */

using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Collections;
using System.IO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using BusinessRule.DTO;
using System.Configuration;

public class BomRquestCancelVue3PageHandler : IHttpHandler, IRequiresSessionState
{
    class Result
    {
        public object data { get; set; }
        public Meta meta { get; set; }
        public int total { get; set; }
        public class Meta
        {
            public int status;
            public string msg;
            public Meta(int status, string msg)
            {
                this.status = status;
                this.msg = msg;
            }
        }
    }

    CurrentUserInfo m_UserInfo = new CurrentUserInfo();
    BusinessRule.IBusiness.uLMSCommonIBusiness m_Common = BusinessRule.BusinessFactory.uMESBusinessFactory.instance.GetuLMSCommonObject();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getUserInfo":
                        r = getUserInfo();//查询当前用户信息
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getData":
                        r = getData(jObject);//查询数据
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "saveCancleData":
                        r = saveCancleData(jObject);//撤销
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    Result getUserInfo()
    {
        Result r = new Result();
        r.data = m_UserInfo;
        r.total = 0;
        r.meta = m_UserInfo == null ? new Result.Meta(500, "当前未登录") : new Result.Meta(200, "请求成功");
        return r;
    }

    Result getData(JObject jObject)
    {
        string sql = @"
SELECT t.id,t.ismeshandle,t.isuse,t.methodname,e.fullname,t.createdate,e2.fullname cancleemp,t.lastchangedate,
       cci.mfgordername,cci.togetherflag,cci.containerid,cci.containername,cci.productname,cci.productdescription,cci.qty,
       cci.workflowname || ':' || cci.workflowrevision workflowinfo,
       DECODE(cci.containertype,'2','批量加工','3','批量带子序号',7,'单件加工') containertype,cci.plannedstartdate,cci.plannedcompletiondate,
       ws.workflowstepname,aps.apsplandetailid
FROM sync_sendto_wms t
INNER JOIN apsplandetail aps ON aps.apsplandetailid = t.uniquecolvalue
INNER JOIN containercurrentinfo cci ON cci.containerid = aps.containerid
LEFT JOIN workflowstep ws ON ws.workflowstepid = aps.workflowstepid
LEFT JOIN employee e ON e.employeeid = t.create_emp
LEFT JOIN employee e2 ON e2.employeeid = t.lastchange_emp
WHERE t.ismeshandle = 1 AND t.methodname = '配套单下发'";
        //主制分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //件号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname LIKE '%{0}%'", jObject["productname"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername LIKE '%{0}%'", jObject["mfgordername"].ToString());
        }

        //批次号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername LIKE '%{0}%'", jObject["containername"].ToString());
        }

        //状态
        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            sql += string.Format(" AND t.isuse = '{0}'", jObject["status"].ToString());
        }

        uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(jObject["currentPage"]);//页码
        paraPage.PageSize = Convert.ToInt32(jObject["pageSize"]);//每页页数
        paraPage.strSQL = sql;
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        DataTable dtResult = result.DBTable;

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(result.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result saveCancleData(JObject jObject)
    {
        string ToAppID_WMS = ConfigurationManager.AppSettings["ToAppID_WMS"].ToString();
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(jObject["postData"].ToString());
        ArrayList sqlList = new ArrayList();
        foreach (DataRow dr in dtPostData.Rows)
        {
            Dictionary<string, string> para = new Dictionary<string, string>();
            para["bizDataNo"] = dr["mfgordername"].ToString();//生产订单号
            para["docNo"] = "";//业务流水号
            para["batchNum"] = dr["containername"].ToString();//批次号
            para["status"] = "撤销出库";
            string json = JsonConvert.SerializeObject(para);

            string insertSql = @"
INSERT INTO sync_sendto_wms(methodname,json,toappid,tablename,uniquecolname,uniquecolvalue,create_emp)
VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')";

            if (m_UserInfo == null)
            {
                m_UserInfo = m_Common.GetUserInfo(jObject["employeename"].ToString(), "");
            }

            insertSql = string.Format(insertSql,
                "配套单撤销",
                json,
                ToAppID_WMS,
                "apsplandetail",
                "apsplandetailid",
                dr["apsplandetailid"].ToString(),
                m_UserInfo.EmployeeID
            );
            sqlList.Add(insertSql);

            string updateSql = @"UPDATE sync_sendto_wms t SET t.isuse = 1,t.lastchange_emp = '{0}',t.lastchangedate = sysdate WHERE t.id = '{1}'";
            updateSql = string.Format(updateSql, m_UserInfo.EmployeeID, dr["id"].ToString());
            sqlList.Add(updateSql);
        }
        Boolean isSuccess = DatabaseHelper.ExecuteSqlListTran(sqlList);
        
        Result r = new Result();
        r.data = isSuccess;
        r.total = 0;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }
}